﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using System.IO;
using ThanhCongJSC.Models;
using ThanhCongJSC.Helper;
using log4net;

namespace ThanhCongJSC.Controllers
{
    public class AdminController : Controller
    {
        private static ILog _logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        #region Get/Set Session
        private string GetSession(string sessionName)
        {
            if (Session[sessionName] != null)
                return Session[sessionName].ToString();
            else
                return string.Empty;
        }

        private void SetSession(string sessionName, string sessionValue)
        {
            if (string.IsNullOrEmpty(sessionValue))
            {
                Session[sessionName] = null;
                return;
            }

            Session[sessionName] = sessionValue;
            Session.Timeout = 10;
        }
        #endregion

        private bool HaveUserRight()
        {
            return (!string.IsNullOrEmpty(GetSession("UserName")));
        }


        public ActionResult Index()
        {
            if (!HaveUserRight())
                return RedirectToAction("LogIn");
            else
                return RedirectToAction("NewsManagement", new { id = Constant.QueryStringTinTucDuAn });
        }


        #region Quan ly User
        public ActionResult LogIn()
        {
            if (HaveUserRight())
                return RedirectToAction("NewsManagement", new { id = Constant.QueryStringTinTucDuAn });
            else
            {
                return View();
            }
        }

        [HttpPost()]
        public ActionResult LogIn(FormCollection form)
        {
            string userName = Request["inpUserName"];
            string password = Request["inpPassword"];
            bool checkUserLogin = false;
            using(DBThangCongJSCEntities entity=new DBThangCongJSCEntities ())
            {
                UserRepository userRepository = new UserRepository(entity);
                checkUserLogin = userRepository.CheckUserLogin(userName, password);
            }

            if (checkUserLogin)
            {
                SetSession("UserName", userName);
                return RedirectToAction("NewsManagement", new { id = Constant.QueryStringTinTucDuAn });
            }

            ViewData["Error"] = "Tên tài khoản hoặc mật khẩu không hợp lệ!!!!";
            return View();
        }

        public ActionResult LogOut()
        {
            if (HaveUserRight())
                SetSession("UserName", null);

            return RedirectToAction("LogIn");
        }

        public ActionResult ChangePassword()
        {
            if (!HaveUserRight())
                return RedirectToAction("LogIn");
            else
            {
                return View();
            }
        }

        [HttpPost()]
        public ActionResult ChangePassword(FormCollection form)
        {
            string oldPwd = Request["inpOldPassword"];
            string oldPwd2 = Request["inpOldPassword2"];
            if (oldPwd != oldPwd2)
            {
                ViewData["Error"] = "Mật khẩu nhập lại không đúng!!!!";
                return View();
            }

            string newPwd = Request["inpNewPassword"];
            if (string.IsNullOrEmpty(newPwd) || newPwd.Length < 6)
            {
                ViewData["Error"] = "Mật khẩu tối thiểu phải có 6 ký tự!!!!";
                return View();
            }

            bool checkUserLogin = false;
            string userName = GetSession("UserName");
            using (DBThangCongJSCEntities entity = new DBThangCongJSCEntities())
            {
                UserRepository userRepository = new UserRepository(entity);
                checkUserLogin = userRepository.CheckUserLogin(userName, oldPwd);
            }

            if (!checkUserLogin)
            {
                ViewData["Error"] = "Mật khẩu nhập vào không chính xác!!!!";
                return View();
            }

            using (DBThangCongJSCEntities entity = new DBThangCongJSCEntities())
            {
                UserRepository userRepository = new UserRepository(entity);
                userRepository.ChangePassword(userName, newPwd);
                SetSession("UserName", null);
            }
            return RedirectToAction("LogIn");
        }
        #endregion


        #region Quan ly Tin Tuc
        public ActionResult NewsManagement(string id)
        {
            if (!HaveUserRight())
                return RedirectToAction("LogIn");

            ViewData["ContentType"] = id;
            return View();
        }

        public ActionResult ListNews(string id, string strPageIndex, string qTitle)
        {
            int pageSize = Constant.PageSize;
            int pageIndex = Convert.ToInt32(strPageIndex);

            List<Content> listContent;
            using (DBThangCongJSCEntities entity = new DBThangCongJSCEntities())
            {
                ContentRepository contentRepository = new ContentRepository(entity);
                listContent = contentRepository.GetListContentDetailByType(id).ToList<Content>();
            }

            if (!string.IsNullOrEmpty(qTitle))
            {
                int i = 0;
                do
                {
                    var item = listContent[i];
                    string title2 = string.IsNullOrEmpty(item.ContentTitle2) ? string.Empty : item.ContentTitle2;
                    if (item.ContentTitle.Contains(qTitle) || title2.Contains(qTitle))
                    {
                        i++;
                        continue;
                    }

                    listContent.Remove(item);
                } while (i < listContent.Count);
            }

            //var model = source.Skip((PageIndex - 1) * PageSize).Take(PageSize).ToArray();
            var model = listContent.Skip((pageIndex - 1) * pageSize).Take(pageSize);

            int total = listContent.Count;
            ViewData["TotalPage"] = (total % pageSize == 0 ? total / pageSize : total / pageSize + 1).ToString();
            ViewData["PageIndex"] = pageIndex.ToString();
            ViewData["PageSize"] = pageIndex.ToString();
            ViewData["ContentType"] = id;

            return View(model);
        }

        public ActionResult AddEditNews(int id, string contentType)
        {
            if (!HaveUserRight())
                return RedirectToAction("LogIn");

            Content model = null;
            if (id == 0)
                model = new Content("", "", "", "", "", "", "", 0, DateTime.Now);
            else if (id > 0)
            {
                using (DBThangCongJSCEntities entity = new DBThangCongJSCEntities())
                {
                    ContentRepository contentRepository = new ContentRepository(entity);
                    model = contentRepository.GetFullContentByID(id);
                }
            }

            ViewData["ContentType"] = contentType;
            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult AddEditNews(Content obj)
        {
            string contentType = Request.Form["content-type"];
            if (!ModelState.IsValid)
            {
                ViewData["ContentType"] = contentType;
                return RedirectToAction("AddEditNews", new { id = obj.ContentID, contentType = contentType });
            }

            // tinh toan gia tri cho content-code va content-image-url
            obj.ContentCode = contentType + "-" + ThanhCongJSC.Helper.Util.GenerateCodeByTitle(obj.ContentTitle);
            obj.ContentDetail = HttpUtility.HtmlDecode(obj.ContentDetail);
            obj.ContentDetail2 = HttpUtility.HtmlDecode(obj.ContentDetail2);

            obj.ContentID = int.Parse(Request.Form["ContentID"]);
            HttpPostedFileBase file = Request.Files[0];
            string fileName = string.Empty;
            if (file.ContentLength > 0)
            {
                fileName = obj.ContentID + ".";
                string[] temp = file.FileName.Split(new char[] { '.' });
                fileName += temp[1];
                obj.ContentImage = fileName;
            }
           
            using (DBThangCongJSCEntities entity = new DBThangCongJSCEntities())
            {
                ContentRepository contentRepository = new ContentRepository(entity);
                // them tin tuc moi
                if (obj.ContentID == 0)
                    contentRepository.AddNewContentFull(obj, contentType);
                else
                    contentRepository.UpdateContentFull(obj);
            }

            // upload hinh anh
            if (file.ContentLength > 0)
            {
                string savedFileName = Path.Combine(
                   Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                   Constant.ImageFolderNews),
                   Path.GetFileName(obj.ContentImage));
                file.SaveAs(savedFileName);
            }

            return RedirectToAction("NewsManagement", new { id = contentType });
        }
        #endregion


        #region Quan ly Tuyen Dung
        public ActionResult RecruitManagement(string id)
        {
            Content model = null;
            using (DBThangCongJSCEntities entity = new DBThangCongJSCEntities())
            {
                ContentRepository contentRepository = new ContentRepository(entity);
                model = contentRepository.GetFullContentByCode(id);
            }

            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult RecruitManagement(Content obj)
        {
            obj.ContentDetail = HttpUtility.HtmlDecode(obj.ContentDetail);
            obj.ContentDetail2 = HttpUtility.HtmlDecode(obj.ContentDetail2);
            obj.ContentID = int.Parse(Request.Form["ContentID"]);

            using (DBThangCongJSCEntities entity = new DBThangCongJSCEntities())
            {
                ContentRepository contentRepository = new ContentRepository(entity);
                contentRepository.UpdateRecruitment(obj);
            }

            return RedirectToAction("Index");
        }
        #endregion


        #region Quan ly Du An
        public ActionResult ProjectManagement(string id)
        {
            if (!HaveUserRight())
                return RedirectToAction("LogIn");

            ViewData["ContentType"] = id;
            return View();
        }

        public ActionResult ListProject(string id, string strPageIndex, string qTitle)
        {
            int pageSize = Constant.PageSize;
            int pageIndex = Convert.ToInt32(strPageIndex);

            List<Content> listContent;
            using (DBThangCongJSCEntities entity = new DBThangCongJSCEntities())
            {
                ContentRepository contentRepository = new ContentRepository(entity);
                listContent = contentRepository.GetListContentDetailByType(id).ToList<Content>();
            }

            if (!string.IsNullOrEmpty(qTitle))
            {
                int i = 0;
                do
                {
                    var item = listContent[i];
                    string title2 = string.IsNullOrEmpty(item.ContentTitle2) ? string.Empty : item.ContentTitle2;
                    if (item.ContentTitle.Contains(qTitle) || title2.Contains(qTitle))
                    {
                        i++;
                        continue;
                    }

                    listContent.Remove(item);
                } while (i < listContent.Count);
            }

            var model = listContent.Skip((pageIndex - 1) * pageSize).Take(pageSize);

            int total = listContent.Count;
            ViewData["TotalPage"] = (total % pageSize == 0 ? total / pageSize : total / pageSize + 1).ToString();
            ViewData["PageIndex"] = pageIndex.ToString();
            ViewData["PageSize"] = pageIndex.ToString();
            ViewData["ContentType"] = id;

            return View(model);
        }

        public ActionResult AddEditProject(int id, string contentType)
        {
            if (!HaveUserRight())
                return RedirectToAction("LogIn");

            Content model = null;
            if (id == 0)
                model = new Content("", "", "", "", "", "", "", 0, DateTime.Now);
            else if (id > 0)
            {
                using (DBThangCongJSCEntities entity = new DBThangCongJSCEntities())
                {
                    ContentRepository contentRepository = new ContentRepository(entity);
                    model = contentRepository.GetFullContentByID(id);
                }
            }

            ViewData["ContentType"] = contentType;
            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult AddEditProject(Content obj)
        {
            obj.ProjectStartDate = DateTime.Parse(Request.Form["ProjectStartDate"], new System.Globalization.CultureInfo("vi-Vn"));
            string contentType = Request.Form["content-type"];

            // tinh toan gia tri cho content-code va content-image-url
            obj.ContentCode = contentType + "-" + ThanhCongJSC.Helper.Util.GenerateCodeByTitle(obj.ContentTitle);
            obj.ContentDetail = HttpUtility.HtmlDecode(obj.ContentDetail);
            obj.ContentDetail2 = HttpUtility.HtmlDecode(obj.ContentDetail2);

            obj.ContentID = int.Parse(Request.Form["ContentID"]);
            HttpPostedFileBase file = Request.Files[0];
            string fileName = string.Empty;
            if (file.ContentLength > 0)
            {
                fileName = obj.ContentID + ".";
                string[] temp = file.FileName.Split(new char[] { '.' });
                fileName += temp[1];
                obj.ContentImage = fileName;
            }


            using (DBThangCongJSCEntities entity = new DBThangCongJSCEntities())
            {
                ContentRepository contentRepository = new ContentRepository(entity);
                // them tin tuc moi
                if (obj.ContentID == 0)
                    contentRepository.AddNewProjectFull(obj, contentType);
                else
                    contentRepository.UpdateProjectFull(obj);
            }

            // upload hinh anh
            if (file.ContentLength > 0)
            {
                string savedFileName = Path.Combine(
                   Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                   Constant.ImageFolderProject),
                   Path.GetFileName(obj.ContentImage));
                file.SaveAs(savedFileName);
            }

            return RedirectToAction("ProjectManagement", new { id = contentType });
        }
        #endregion


        public ActionResult DeleteContent(string id, bool isProject)
        {
            string imageName = string.Empty;
            using (DBThangCongJSCEntities entity = new DBThangCongJSCEntities())
            {
                ContentRepository contentRepository = new ContentRepository(entity);
                imageName = contentRepository.DeleteContentsByListId(id, isProject);
            }

            if (!string.IsNullOrEmpty(imageName))
            {
                string deleteFileName = Path.Combine(
                  Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                  isProject ? Constant.ImageFolderProject : Constant.ImageFolderNews),
                  imageName);
                System.IO.File.Delete(deleteFileName);
            }

            return Content("");
        }

        [HttpPost()]
        public JsonResult ChangeLanguage(string lang)
        {
            Session["CultureInfo"] = lang;
            return this.Json(new { mess = "Successfully" }, JsonRequestBehavior.AllowGet);
        }
    }
}
